from PySide6.QtWidgets import (
    QMainWindow, QVBoxLayout, QHBoxLayout, QWidget,
    QStackedWidget
)

from core.router import Router
from view.upload_module import UploadModule
from view.disk_module import DiskModule
from view.setting_module import SettingModule
from view.components.server_widget import ServerWidget
from core.server_manager import ServerManager

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.server_manager = ServerManager()

        self.setWindowTitle("测试工具")
        self.setMinimumSize(1080, 720)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QHBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 左侧侧边栏
        sidebar = QWidget()
        sidebar.setObjectName("sidebar") 
        sidebar.setFixedWidth(160)

        sidebar_layout = QVBoxLayout(sidebar)
        sidebar_layout.setContentsMargins(10, 20, 10, 20)
        sidebar_layout.setSpacing(10)      

        # 按钮区
        self.module_buttons_widget = QWidget()
        self.module_buttons_layout = QVBoxLayout(self.module_buttons_widget)
        sidebar_layout.addWidget(self.module_buttons_widget)
        self.module_buttons_layout.setSpacing(8)
        self.module_buttons_layout.setContentsMargins(0, 0, 0, 0)
        sidebar_layout.addStretch()
        main_layout.addWidget(sidebar)

        # 右侧内容
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)

        self.server_widget = ServerWidget(title="目标服务器", server_manager = self.server_manager)
        self.server_widget.setMaximumHeight(250)
        right_layout.addWidget(self.server_widget)

        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setContentsMargins(0, 0, 0, 0)
        right_layout.addWidget(self.stacked_widget)
        main_layout.addWidget(right_widget, 1)

        # 模块路由管理
        self.router = Router(self.stacked_widget, self.module_buttons_layout, self.server_manager)
        self.register_modules()

    def register_modules(self):
        self.router.register("软件包校验/部署", UploadModule, "assets/upload.ico")
        self.router.register("磁盘检测", DiskModule, "assets/disk.ico")
        self.router.register("设置", SettingModule, "assets/setting.ico")

        self.router.activate("软件包校验/部署")
        self.router.module_changed.connect(self.on_module_changed)

    def on_module_changed(self, module_name):
        module = self.router.get_module(module_name)
        if hasattr(module, "need_server_widget") and not module.need_server_widget:
            self.server_widget.hide()
        else:
            self.server_widget.show()
